const BASR_URL = 'http://192.168.1.29:8080'

/**
 * {url:'',method:'',data:xx}
 */
export const request = (options) => {
	return new Promise((resolve, rejects) => {
		//获取登录过期时间，毫秒
		let login_expire_time = uni.getStorageSync('login_expire_time')
		if (login_expire_time && login_expire_time > new Date().getTime()) {
			//说明本地存储的认证的令牌还没有过期
			handleRequest(options, resolve, rejects)
		} else {
			uni.login({
				provider: 'weixin', //使用微信登录
				success: function(loginRes) {
					uni.request({
						url: BASR_URL + '/mp/login',
						data: {
							code: loginRes.code
						},
						method: "POST",
						header: {
							'content-type': 'application/x-www-form-urlencoded'
						},
						success: (res) => {
							uni.setStorage({
								key: 'user_info',
								data: res.data.data,
								success: function() {
									uni.setStorage({
										key: 'login_expire_time',
										data: new Date()
											.getTime() + 3600 *
											1000
									})
									handleRequest(options, resolve,
										rejects)
								}
							});
						}
					});
				}
			});
		}
	})
}



export const handleRequest = (options, resolve, rejects) => {
	uni.request({
		url: BASR_URL + options.url,
		data: options.data,
		method: options.method,
		header: {
			'content-type': 'application/json',
			'openid': uni.getStorageSync('user_info').openid,
			'mp_token': uni.getStorageSync('user_info').session_key
		},
		success: (res) => {
			return resolve(res.data)
		},
		fail: err => {
			return rejects(err)
		},
		complete: () => {
			uni.hideLoading()
		}
	});
}

export const getAllBanners = () => {
	return request({
		url: '/mp/banners',
		method: 'GET'
	})
}
export const getAllCategories = () => {
	return request({
		url: '/mp/categories',
		method: 'GET'
	})
}
export const getAllModels = () => {
	return request({
		url: '/mp/models',
		method: 'GET'
	})
}
export const getAllCategoryItems = (item) => {
	return request({
		url: '/mp/categories/' + item,
		method: 'GET'
	})
}

export const chat = (data) => {
	return request({
		url: '/mp/chat',
		method: 'POST',
		data: data
	})
}
export const getAllRecords = (pageNum) => {
	return request({
		url: '/mp/records?subject=all&pageNum=' + pageNum,
		method: 'GET'
	})
}